package com.feisuanyz.service.validation.impl;

import com.feisuanyz.dto.RestResult;
import com.feisuanyz.dto.TicketValidationQuery;
import com.feisuanyz.entity.EventManagement;
import com.feisuanyz.entity.TicketManagement;
import com.feisuanyz.repository.EventManagementRepository;
import com.feisuanyz.repository.TicketManagementRepository;
import com.feisuanyz.service.validation.TicketValidationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 票务验证服务实现类
 */
@Service
@Slf4j
public class TicketValidationServiceImpl implements TicketValidationService {

    @Autowired
    private TicketManagementRepository ticketManagementRepository;

    @Autowired
    private EventManagementRepository eventManagementRepository;

    @Override
    public RestResult validateTicket(TicketValidationQuery query, String operation) {
        if ("edit".equalsIgnoreCase(operation) || "delete".equalsIgnoreCase(operation)) {
            if (query.getTicketId() == null) {
                return new RestResult("000001", "票务ID不能为空", null);
            }
            TicketManagement ticket = ticketManagementRepository.findById(query.getTicketId()).orElse(null);
            if (ticket == null) {
                return new RestResult("000001", "票务ID不存在", null);
            }
        }

        EventManagement event = eventManagementRepository.findById(query.getEventId()).orElse(null);
        if (event == null) {
            return new RestResult("000001", "关联的事件ID不存在", null);
        }

        if (query.getAvailableTickets() <= 0) {
            return new RestResult("000001", "可用票数必须为正整数", null);
        }

        if (query.getRemainingTickets() < 0) {
            return new RestResult("000001", "剩余票数必须为非负整数", null);
        }

        if (query.getRemainingTickets() > query.getAvailableTickets()) {
            return new RestResult("000001", "剩余票数不能大于可用票数", null);
        }

        return new RestResult("000000", "调用成功", null);
    }
}